import cookie from 'js-cookie';
import getUploadToken from "@/service/upload/token";

const tokenKey: string = 'upload_token';
const expiresKey: string = 'upload_token_expires';

/*
* 获取uuid
* */
const S4 = () => (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
export const uuid = (len: number = 6) => Array.from({ length: len }).map(() => S4()).join('-');

export const getFileType = (filePath: string) => {
  const startIndex = filePath.lastIndexOf('.');
  return startIndex !== -1 ? filePath.substring(startIndex + 1, filePath.length).toLowerCase() : '';
}

/*
* 获取上传token
* */
export const getToken = async () => {
  const current = Date.now() / 1000;
  const _token = cookie.get(tokenKey) || '';
  const _expiresIn = cookie.get(expiresKey) || 0;
  /* 检查token是否已经过期 */
  if (_token && current < (+_expiresIn) + 60) return _token;
  const { token, expiresIn } = await getUploadToken();
  cookie.set(tokenKey, token);
  cookie.set(expiresKey, `${expiresIn}`);
  return token;
}

/*
* 是否为原生正则
* */
export const isReg = (value: string | RegExp) => {
  return Object.prototype.toString.call(value) === '[object RegExp]';
}
